package com.tool.imp.ia;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.ss.usermodel.Row;

import com.tool.BillType;
import com.tool.DataCenterVO;
import com.tool.imp.BillVO;
import com.tool.imp.ImportBase;
import com.tool.imp.KeyGenerator;
import com.tool.imp.ParseExcelException;
import com.tool.util.ToolConstUtils;

/**
 * AP测试道具导入实现类
 * 
 * @author Evan.Hu
 * 
 */
public class ProInBillImp extends ImportBase {
	/**
	 * 定义Excel读取列 对应字段
	 */
	protected static Map<Integer, String> xlsMap;

	public ProInBillImp(DataCenterVO dbVo, String xlsPath, Boolean fileFlag) {
		super(BillType.IA_CCP, dbVo, xlsPath, fileFlag);

	}

	static {

		xlsMap = new HashMap<Integer, String>();

		// 定义读取填充序列,仅作为参考
		xlsMap.put(0, "vbillcode");
		xlsMap.put(4, "crdcenterid");
		xlsMap.put(5, "cwarehouseid");
		xlsMap.put(6, "cdeptid");
		xlsMap.put(7, "ccustomvendorid");
		xlsMap.put(8, "vnote");
		xlsMap.put(9, "coperatorid");
		xlsMap.put(10, "tmaketime");
		xlsMap.put(17, "entries.cinvbasid");
		xlsMap.put(21, "entries.nmoney");
		xlsMap.put(22, "entries.nprice");
		xlsMap.put(23, "entries.nnumber");

	}

	/**
	 * 将两个VO的分录进行合并保存在destVo对象中
	 * 
	 * @param destVo
	 * @param srcVo
	 */
	protected void compositEntry(BillVO destVo, BillVO srcVo) {
		ProInBillVO destVo2 = (ProInBillVO) destVo;
		ProInBillVO srcVo2 = (ProInBillVO) srcVo;

		destVo2.getEntries().addAll(srcVo2.getEntries());
	}

	/**
	 * 解析（或者也可以检查基础资料）
	 * 
	 * @return
	 */
	protected BillVO parseRow(Row row) throws ParseExcelException {
		ProInBillVO record = new ProInBillVO();
		// 按照定义的文件，进行Excel文件读取
		// 单据号
		String billCode = getCellValue(row, 0);
		record.setVbillcode(billCode);
		// 公司
		String orgId = getCellValue(row, 1);
		final String corpBaseData = cachMap.getCorp(orgId);

		// ==============校验示例-Start=====
		if (isEmptyString(orgId)) {
			// 基本类型数据无效
			// TODO 第二个参数，根据具体取数列来定
			throw new ParseExcelException(rowInx, 1, "orgId字段不能为空");
		}
		if (isEmptyObject(corpBaseData)) {
			// 基础资料为无效

			throw new ParseExcelException(rowInx, 1, "基础资料获取失败-" + orgId);
		}
		// ==============校验示例-End=====

		record.setPk_corp(corpBaseData);
		// 库存组织
		String rdCenterId = cachMap.getStorageOrgUnit(getCellValue(row, 4));
		record.setCrdcenterid(rdCenterId);
		// 库存组织
		record.setCstockrdcenterid(rdCenterId);
		// 仓库
		record.setCwarehouseid(cachMap.getWarehouse(getCellValue(row, 5)));
		// 部门
		record.setCdeptid(cachMap.getDept(getCellValue(row, 6)));
		// 客商基本档案
		String cusSuppNumber = getCellValue(row, 7);
		record.setCcustomvendorbasid(cachMap.getCustSuppBasID(cusSuppNumber));
		// 客商管理档案
		String cusSuppStr = cachMap.getCustSupp(cusSuppNumber, corpBaseData);
		record.setCcustomvendorid(cusSuppStr);
		// 备注
		record.setVnote(getCellValue(row, 8));
		String personNumber = getCellValue(row, 9);
		record.setCemployeeid(cachMap.getPerson(personNumber));
		// 制单人(用户)
		String operatorId = cachMap.getUser(personNumber);
		record.setCoperatorid(operatorId);
		// 最后操作人
		record.setClastoperatorid(operatorId);
		// 单据日期
		Date date = getDateValue(row, 10);
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		record.setDbilldate(DateToString2(date));
		// 制单时间
		String maketimeStr = getTimeStrValue(row, 10);
		record.setTmaketime(maketimeStr);
		// 最后更新时间
		record.setTlastmaketime(maketimeStr);
		// 会计年份
		record.setCaccountyear(new Integer(cal.get(Calendar.YEAR)).toString());
		// 会计月份
		record.setCaccountmonth(new Integer(cal.get(Calendar.MONTH) + 1).toString());
		ProInBillEntryVO entry = new ProInBillEntryVO();
		record.getEntries().add(entry);
		entry.setPk_corp(cachMap.getCorp(getCellValue(row, 1)));
		entry.setCrdcenterid(cachMap.getStorageOrgUnit(getCellValue(row, 4)));
		entry.setVbillcode(billCode);
		String invBasDoc = new String();
		invBasDoc = cachMap.getInvBasDoc(getCellValue(row, 17));
		entry.setCinvbasid(invBasDoc);
		entry.setCinventoryid(cachMap.getInvManageDoc(invBasDoc));
		// 客商管理档案ID
		entry.setCvendorid(cusSuppStr);
		BigDecimal money = convertToDecimal(getCellValue(row, 21));
		// 金额
		entry.setNmoney(money);
		// 计划金额
		entry.setNplanedmny(money);
		BigDecimal price = convertToDecimal(getCellValue(row, 22));
		// 单价
		entry.setNprice(price);
		// 计划单价
		entry.setNplanedprice(price);
		entry.setNnumber(convertToDecimal(getCellValue(row, 23)));
		// 业务日期
		entry.setDbizdate(getCellValue(row, 10));
		// TODO
		// 需要再次检查基础资料完整性

		return record;
	}

	/**
	 * 
	 */
	protected void process() throws Exception {
		// 某条单据保存不成功，将继续执行设置保存操作

		for (BillVO billVo : records) {
			ProInBillVO iaVO = (ProInBillVO) billVo;

			// 设置校验等信息
			setDefaultValue(iaVO);

			// 重复性校验
			boolean isDup = checkNumberDuplicate(iaVO);

			if (isDup) {
				getMsgBean().getErrList().add(iaVO.getVbillcode() + "|单据号重复");
			} else {
				// 保存VO至数据库
				boolean isSuc = iaVO.saveVO(dbVo);
				if (isSuc) {
					getMsgBean().getSucList().add(iaVO.getVbillcode());
				} else {
					getMsgBean().getErrList().add(iaVO.getVbillcode() + "|保存失败");
				}
			}
		}
	}

	/**
	 * 设置默认值
	 * 
	 * @param vo
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	private void setDefaultValue(ProInBillVO vo) {
		// 生成ID
		String billID = KeyGenerator.randomKey20();
		vo.setCbillid(billID);
		vo.setCbilltypecode(ToolConstUtils.CCPRKD);
		vo.setIprintcount(0);
		// 收发类别
		vo.setCdispatchid(cachMap.getDispatch(ToolConstUtils.DIS_IN));
		// 业务类型,暂置为空
		vo.setCbiztypeid(null);
		vo.setIdebtflag(-1);
		vo.setBauditedflag("N");
		vo.setBdisableflag("N");
		vo.setBestimateflag("N");
		vo.setBoutestimate("N");
		vo.setBwithdrawalflag("N");
		// 收发类别,收为0,发为1
		vo.setFdispatchflag(0);

		for (int i = 0, size = vo.getEntries().size(); i < size; i++) {
			ProInBillEntryVO entry = vo.getEntries().get(i);
			entry.setCbill_bid(KeyGenerator.randomKey20());
			entry.setCbillid(billID);
			entry.setIrownumber(i);
			// 单据类型
			entry.setCbilltypecode(ToolConstUtils.CGRKD);
			// 计价方式
			entry.setFpricemodeflag(3);
			// 是否批量核算
			entry.setBauditbatchflag("N");
			entry.setBlargessflag("N");
			// 时间戳
			entry.setTs(DateToString(new Date()));
		}
	}
}
